import { Button, Descriptions, message, Divider, Empty } from "antd";
import FirstTitle from "@/components/FirstTitle";
import EffectContainer from "@/components/effectContainer";
import { useEffect, useState } from "react";
import moment from "moment";
import Code from "@/components/code";
import SubTitle from "@/components/subTitle";
import { getCode } from "@/api/codeApi.ts";
import { Description } from "@/components/description";
export const ReadAndSaveFile = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const [items, setItems] = useState([
    {
      key: "1",
      label: "名称",
      children: "",
    },
    {
      key: "2",
      label: "最后更新时间",
      children: "",
    },
    {
      key: "3",
      label: "大小",
      children: "",
    },
    {
      key: "4",
      label: "类型",
      children: "",
    },
  ]);
  const [content, setContent] = useState("");
  const [readFileCode, setReadFileCode] = useState("");
  const [saveFileCode, setSaveFileCode] = useState("");
  useEffect(() => {
    getCode("/readAndSaveFile/read.txt").then(({ data }) => {
      setReadFileCode(data);
    });
    getCode("/readAndSaveFile/save.txt").then(({ data }) => {
      setSaveFileCode(data);
    });
  }, []);
  const chooseFile = async () => {
    try {
      // 打开文件选择对话框
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      //@ts-expect-error
      const [fileHandle] = await window.showOpenFilePicker();

      // 读取文件内容
      const file = await fileHandle.getFile();
      const contents = await file.text();
      console.log("文件内容:", file, contents);
      const size = file.size / 1000;
      const lastModified = moment(file.lastModified).format(
        "YYYY/MM/DD HH:mm:ss",
      );
      setContent(contents);
      setItems([
        {
          key: "1",
          label: "名称",
          children: file.name,
        },
        {
          key: "2",
          label: "最后更新时间",
          children: lastModified,
        },
        {
          key: "3",
          label: "大小",
          children: `${size} kB`,
        },
        {
          key: "4",
          label: "类型",
          children: file.type,
        },
      ]);
    } catch (error) {
      console.error("发生错误:", error);
    }
  };
  const saveFile = async () => {
    if (content == "") {
      messageApi.open({
        type: "warning",
        content: "请先在上一栏选择文件!",
      });
      return;
    }
    // 打开保存文件对话框
    const saveOptions = {
      suggestedName: "saved-file.txt",
      types: [
        {
          description: "Text files",
          accept: {
            "text/plain": [".txt"],
          },
        },
      ],
    };
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    //@ts-expect-error
    const saveHandle = await window.showSaveFilePicker(saveOptions);

    // 写入文件内容 keepExistingData 可写入
    const writableStream = await saveHandle.createWritable({
      keepExistingData: true,
    });
    await writableStream.write(content);
    await writableStream.close();
    messageApi.open({
      type: "success",
      content: "文件保存完成!",
    });
  };
  return (
    <>
      {contextHolder}
      <FirstTitle title="读取系统文件" />
      <SubTitle title="读取"></SubTitle>
      <Description
        info={<h2 style={{ color: "red" }}>*该功能需要使用https</h2>}
      />
      <EffectContainer
        effect={
          <div style={{ padding: "10px" }}>
            <Button type="primary" onClick={chooseFile}>
              选择文件
            </Button>
            <Divider />
            {content !== "" ? (
              <div>
                <Descriptions title="文件内容" items={items} />
                <Code content={content}></Code>
              </div>
            ) : (
              <Empty
                description={"暂未选择文件"}
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            )}
          </div>
        }
        code={<Code content={readFileCode}></Code>}
      ></EffectContainer>

      <FirstTitle title="保存系统文件" />
      <SubTitle title="保存"></SubTitle>

      <EffectContainer
        effect={
          <div style={{ padding: "10px" }}>
            <Button type="primary" onClick={saveFile}>
              保存文件
            </Button>
          </div>
        }
        code={<Code content={saveFileCode}></Code>}
      ></EffectContainer>
    </>
  );
};
